package com.cetcs.kmga.dataManager.util.socket;

import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.TextMessage;

import java.io.IOException;
import java.util.Date;

/**
 * 建立连接后实现的任务
 *
 * @author xutao
 * @version V1.0 创建时间：2017-10-23 15:59
 *          Copyright 2017 by CETC
 */
public class AfterConnectionEstablishedTask implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(AfterConnectionEstablishedTask.class);
    String userId;
    String message;

    public AfterConnectionEstablishedTask(String userId, String message) {
        this.userId = userId;
        this.message = message;
    }

    @Override
    public void run() {
        logger.info("开始推送消息给用户:" + userId + "。。。");
        if (!Strings.isNullOrEmpty(userId) && !Strings.isNullOrEmpty(message)) {
            UserSocket userSocket = WSSessionLocalCache.get(userId);
            TextMessage reMessage = new TextMessage(message);
            try {
                if (null != userSocket) {
                    //推送消息
                    userSocket.getWebSocketSession().sendMessage(reMessage);
                    //更新推送时间
                    userSocket.setLastSendTime(new Date());
                    logger.info("完成推送新消息给用户:" + userSocket.getUserId() + "。。。");
                }

            } catch (IOException e) {
                logger.error(e.toString());
                logger.info("站内消息推送失败。。。" + e.toString());
            }
        }
        logger.info("结束推送消息给" + userId + "。。。");
    }
}
